<?php
// api/courseofferings.php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { exit(0); }

require_once 'db.php';

$method = $_SERVER['REQUEST_METHOD'];
$offeringID = $_GET['OfferingID'] ?? null;

switch($method) {
    case "GET":
        try {
             // Join to get CourseName and TeacherName for better display
             $sql = "SELECT co.*, c.CourseName, t.Name AS TeacherName
                    FROM CourseOffering co
                    JOIN Course c ON co.CourseID = c.CourseID
                    JOIN Teacher t ON co.TeacherID = t.TeacherID";

            if ($offeringID !== null) {
                $sql .= " WHERE co.OfferingID = ?";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$offeringID]);
                $offering = $stmt->fetch();
                if ($offering) { echo json_encode($offering); }
                else { http_response_code(404); echo json_encode(["error" => "Course offering not found"]); }
            } else {
                 // Optional: Add filtering by year, semester, etc. via query params
                 // e.g., if(isset($_GET['year'])) { $sql .= " WHERE co.Year = ?"; $params[] = $_GET['year']; }
                $sql .= " ORDER BY co.Year DESC, co.Semester ASC, c.CourseName ASC";
                $stmt = $pdo->query($sql); // Assuming no params for general list yet
                $offerings = $stmt->fetchAll();
                echo json_encode($offerings);
            }
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(["error" => "Failed to retrieve course offerings", "details" => $e->getMessage()]);
        }
        break;

    case "POST":
        $data = json_decode(file_get_contents("php://input"), true);
        if (!isset($data['CourseID'], $data['TeacherID'], $data['Year'], $data['Semester'], $data['Capacity'])
            || empty($data['CourseID']) || empty($data['TeacherID']) || empty($data['Year']) || empty($data['Semester']) || !is_numeric($data['Capacity'])) {
            http_response_code(400);
            echo json_encode(["error" => "Missing or invalid required fields (CourseID, TeacherID, Year, Semester, Capacity)"]);
            exit;
        }
         if (!in_array($data['Semester'], ['spring', 'autumn'])) {
             http_response_code(400); echo json_encode(["error" => "Invalid semester"]); exit;
         }
         // Add checks if CourseID and TeacherID actually exist? Good practice.

        try {
            $stmt = $pdo->prepare("INSERT INTO CourseOffering (CourseID, TeacherID, Year, Semester, Capacity) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([
                $data['CourseID'],
                $data['TeacherID'],
                $data['Year'],
                $data['Semester'],
                $data['Capacity']
            ]);
            http_response_code(201);
            echo json_encode(["success" => true, "OfferingID" => $pdo->lastInsertId()]);
        } catch (PDOException $e) {
            http_response_code(500);
             if ($e->getCode() == '23000') { // FK violation if CourseID or TeacherID is invalid
                 http_response_code(400);
                 echo json_encode(["error" => "Database constraint violation (e.g., invalid CourseID or TeacherID)", "details" => $e->getMessage()]);
             } else {
                 echo json_encode(["error" => "Failed to add course offering", "details" => $e->getMessage()]);
             }
        }
        break;

    case "PUT":
         if ($offeringID === null) {
            http_response_code(400); echo json_encode(["error" => "OfferingID is required for update"]); exit;
        }
        $data = json_decode(file_get_contents("php://input"), true);
        if (!isset($data['CourseID'], $data['TeacherID'], $data['Year'], $data['Semester'], $data['Capacity'])
            || empty($data['CourseID']) || empty($data['TeacherID']) || empty($data['Year']) || empty($data['Semester']) || !is_numeric($data['Capacity'])) {
            http_response_code(400);
            echo json_encode(["error" => "Missing or invalid required fields (CourseID, TeacherID, Year, Semester, Capacity)"]);
            exit;
        }
         if (!in_array($data['Semester'], ['spring', 'autumn'])) {
             http_response_code(400); echo json_encode(["error" => "Invalid semester"]); exit;
         }
         // Add checks if CourseID and TeacherID exist? Good practice.

        try {
            $stmt = $pdo->prepare("UPDATE CourseOffering SET CourseID = ?, TeacherID = ?, Year = ?, Semester = ?, Capacity = ? WHERE OfferingID = ?");
            $success = $stmt->execute([
                 $data['CourseID'],
                 $data['TeacherID'],
                 $data['Year'],
                 $data['Semester'],
                 $data['Capacity'],
                 $offeringID
            ]);
             if ($success && $stmt->rowCount() > 0) {
                 echo json_encode(["success" => true, "message" => "Course offering updated"]);
            } elseif($success) {
                 http_response_code(404);
                 echo json_encode(["error" => "Course offering not found or no changes made"]);
            } else {
                 http_response_code(500);
                 echo json_encode(["error" => "Failed to update course offering"]);
            }
        } catch (PDOException $e) {
            http_response_code(500);
             if ($e->getCode() == '23000') { // FK violation if CourseID or TeacherID is invalid
                 http_response_code(400);
                 echo json_encode(["error" => "Database constraint violation (e.g., invalid CourseID or TeacherID)", "details" => $e->getMessage()]);
             } else {
                 echo json_encode(["error" => "Failed to update course offering", "details" => $e->getMessage()]);
             }
        }
        break;

    case "DELETE":
        if ($offeringID === null) {
            http_response_code(400); echo json_encode(["error" => "OfferingID is required for deletion"]); exit;
        }
        try {
            $stmt = $pdo->prepare("DELETE FROM CourseOffering WHERE OfferingID = ?");
            $success = $stmt->execute([$offeringID]);
             if ($success && $stmt->rowCount() > 0) {
                echo json_encode(["success" => true, "message" => "Course offering deleted"]);
            } else {
                http_response_code(404);
                echo json_encode(["error" => "Course offering not found"]);
            }
        } catch (PDOException $e) {
             if ($e->getCode() == '23000') { // Foreign key constraint violation (Enrollments)
                 http_response_code(409);
                 echo json_encode(["error" => "Cannot delete offering: Students are enrolled in this offering.", "details" => $e->getMessage()]);
             } else {
                 http_response_code(500);
                 echo json_encode(["error" => "Failed to delete course offering", "details" => $e->getMessage()]);
             }
        }
        break;

    default:
        http_response_code(405);
        echo json_encode(["error" => "Method not allowed"]);
        break;
}
?>